## OppetArkiv doesn't have an open API so let's parse their HTML
require 'date'
require 'time'

module Shin
  module Play
    class Oppetarkiv

      def new
        self
      end

      # Episodes
      def episodes(params={})
        raise MissingArgument, "You are missing the argument 'slug' which is required to use this source." unless params[:slug] != ""

        # What to return
        array = {title: nil, episodes: []}

        total_pages = 999
        (1..total_pages).each do |page_num|
          # Response
          response = Base.get('http://www.oppetarkiv.se/etikett/titel/' + params[:slug].to_s + '/?sida=' + page_num.to_s + '&sort=tid_stigande')
          puts 'http://www.oppetarkiv.se/etikett/titel/' + params[:slug].to_s + '/?sida=' + page_num.to_s + '&sort=tid_stigande'
          raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200

          # Nokogiri parse
          @main_noko = Nokogiri::HTML response.body rescue nil

          # Can't be nil
          if @main_noko != nil
            # Title
            array[:title] = @main_noko.css('span.svt-heading-l').text.strip rescue nil

            # Episodes
            @main_noko.css('div.svtoa-js-searchlist-episodes > article').map do |e|
              @video_id = e.css('a')[0]['href'][/\/video\/(\d+)\//, 1].to_i rescue nil
              @url = e.css('a')[0]['href'] rescue nil
              @season = e.css('h1.svt-text-margin-small').text[/S.song\s+(\d+)/, 1].to_i rescue nil
              @episode = e.css('h2.svt-heading-xxs.svt-text-margin-medium').text[/Avsnitt\s+(\d+)/, 1].to_i rescue nil
              @of_episode = e.css('h2.svt-heading-xxs.svt-text-margin-medium').text[/Avsnitt\s+(\d+)\s+av\s+(\d+)/, 2].to_i rescue nil
              @image = e.css('noscript > img.oaImg')[0]['src'].gsub("ALTERNATES/medium", "ALTERNATES/extralarge") rescue nil

              # Parse published_to
              if e.css('time') != nil and e.css('time') != "" and pat = e.css('time')[0]['datetime']
                @published_on = Time.parse(pat) rescue nil
              end
              
              # No episode info? Possible a subtitle
              if @season < 1 and @episode < 1
                @subtitle = e.css('h2.svt-heading-xxs.svt-text-margin-medium > a')[0]['title'].strip
              else
                @subtitle = e.css('h2.svt-heading-xxs.svt-text-margin-medium > a')[0]['title'].gsub("Avsnitt " + @episode.to_s + ' av ' + @of_episode.to_s + ':', '').gsub("Avsnitt " + @episode.to_s + ' av ' + @of_episode.to_s, '').strip
              end

              array[:episodes] << {id: @video_id, subtitle: @subtitle, image: @image, season: @season, episode: @episode, of_episodes: @of_episode, url: @url, published_on: @published_on}

            end

            # No more pages, break.
            if @main_noko.css('.svtoa-js-search-step-button > span > span.svt_icon--caret-down').to_s == ""
              break
            end
          else
            raise NotValid, "Nokogiri failed to parse the HTML."
          end
        end

        array.to_hashugar
      end

      # Programs
      def programs
        # Response
        response = Base.get('http://www.oppetarkiv.se/kategori/titel')
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200

        # Nokogiri parse
        @main_noko = Nokogiri::HTML response.body rescue nil

        # Foreach programs
        @array = []
        if @main_noko != nil
          @main_noko.css('ul.svtoa-anchor-list.svtColumns-1-2-3-4 > li').map do |p|
            sluge = p.css('a')[0]['href'].strip[/titel\/(.*)\//, 1]
            titlee = p.css('a').text
            @array << {slug: sluge, title: titlee}
          end
        end

        @array.to_hashugar
      end


      # Errors
      class MissingArgument  < StandardError; end
      class HTTPError        < StandardError; end
      class NotValid         < StandardError; end
    end
  end
end
